<?php


if(!defined('IN_JISHIGOU')) {
	exit('invalid request');
}
interface OfferConst {
	/**
	 * 悬赏开始
	 */
	const OFFER_INIT="1";
	/**
	 * 悬赏结贴
	 */
	const OFFER_KONT="2";
	/**
	 * 悬赏过期
	 */
	const OFFER_TIMEOUT="3";

}





class ModuleObject extends MasterObject {

	private $offerList;
	private $count;
	private $Moffer;
	private $wherePart;




	function ModuleObject($config) {

		$this->Moffer = M('offer');
		$this->MasterObject($config);
		$this->Execute();
	}

	function Execute(){
		ob_start();
		$config = $this->Config;
		if(MEMBER_ID < 1){
			$this->Messager("你需要先登录才能继续本操作", 'index.php?mod=login');
		}
		if($config['offer_open']!=1){
			$this->Messager("本应用未开启");
		}

		if(!empty($this->Code)){
			$this->{$this->Code}();
		}else{
			$this->unKnot();
		}


		$body = ob_get_clean();
		$this->ShowBody($body);
	}

	function main(){

		$this->unKnot();
	}
	/**
	 * 未结贴
	 */
	function unKnot(){
		$this->wherePart="status=".OfferConst::OFFER_INIT;

		self::getList();
	}
	/**
	 * 结贴
	 */
	function knot(){
		$this->wherePart="status=".OfferConst::OFFER_KONT;
		self::getList();
	}
	/**
	 * 超时
	 */
	function out(){
		$this->wherePart="status=".OfferConst::OFFER_TIMEOUT;
		self::getList();
	}
	/**
	 * 所有
	 */
	function all(){
		$this->wherePart="1=1";
		self::getList();
	}


	function curPageURL()
	{
		return 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
	}

	private function getList(){

		$this->Title = "悬赏";
		$active[$this->Code]=true;

		$page=$_GET['page'];
		if($page<1){
			$page=1;
		}

		$this->offerList=$this->Moffer->where($this->wherePart)->order('recommend desc,startTime desc')->page($page,10)->select();

		$this->count=$this->Moffer->where($this->wherePart)->count();
		$_config = array(
				'return' => 'array',
		);

		$count=$this->count;
		$page_arr = page($count, 10, self::curPageURL(),$_config);

		$offer_list=$this->offerList;


		$uids=array();
		$i=0;
		foreach ($offer_list as $list){
			$uids[]=$list[uid];

			//取出图片
			$offer=self::getPicUrl($list['content']);
			$offer_list[$i]['images']=$offer['images'];
			$offer_list[$i]['content']=$offer['content'];



			$offer_list[$i]['statusName']=self::getStatusName($offer_list[$i]['status']);
			$i++;
		}
		//取用户头像
		$uids=array_unique($uids);

		$members=self::getUserInfos($uids);




		//右侧智慧达人（分数最多）
		$hotUsers =M('members')->order('extcredits2 desc')->limit(10)->select();

		//热门悬赏（点击量最多）
		$hotOffer=M('offer')->order('clickNum desc')->limit(10)->select();

		include template('/offer/offer_index');
	}
	/**
	 * 取用户头像
	 * @param unknown_type $ids
	 */
	private function getUserInfos($uids){
		$uids=array_unique($uids);
		$users =M('members')->select($uids);
		$members=array();
		foreach ($users as $user){
			$user['face']=$user['face'];
			$members[$user['uid']]=$user;
		}
		return $members;
	}


	private function getPicUrl($content){
		//取出图片
		$pa = '%\[image](.*?)\[/image]%si';
		preg_match_all($pa,$content,$images);

		$contentTemp=$content;
		if(!empty($images[1])){
			$data['images']=M('topic_image')->select(implode(",",$images[1]));
			//替换掉图片标签
			foreach ($images[1] as $img){
				$contentTemp=str_replace("[image]".$img."[/image]","",$contentTemp);
			}
			$contentTemp=str_replace("#分享图片#","",$contentTemp);
		}
		$data['content']=$contentTemp;
		return $data;
	}


	private function getStatusName($code){
		$type=array();
		$type[OfferConst::OFFER_INIT]="进行中";
		$type[OfferConst::OFFER_KONT]="已结束";
		$type[OfferConst::OFFER_TIMEOUT]="已过期";
		return $type[$code];
	}


	/**
	 * 详细内容及回复
	 */
	function offerList(){



		$offerInfo=$this->Moffer->find($_GET['id']);
		$this->Title = $offerInfo['title'];
		//添加点击数
		self::addClickNum($offerInfo);

		//获取图片
		$offer=self::getPicUrl($offerInfo['content']);
		$offerInfo['images']=$offer['images'];
		$offerInfo['content']=$offer['content'];


		//取发布者头像
		$user =M('members')->where('uid='.$offerInfo['uid'])->find();










		$zhb=$offerInfo['num'];

		$page=$_GET['page'];
		if($page<1){
			$page=1;
		}
		$this->wherePart="oid=".$_GET['id'];
		$this->offerList=M("offer_reply")->where($this->wherePart)->page($page,10)->select();
		$this->count=M("offer_reply")->where($this->wherePart)->count();
		$_config = array(
				'return' => 'array',
		);
		$count=$this->count;
		$page_arr = page($count, 10, self::curPageURL(),$_config);
		$offer_list=$this->offerList;



		$uids=array();
		$i=0;
		foreach ($offer_list as $list){
			$uids[]=$list[uid];
			$offer=self::getPicUrl($list['replys']);

			$offer_list[$i]['images']=$offer['images'];
			$offer_list[$i]['replys']=$offer['content'];

			$i++;
		}
		//取用户头像
		$uids=array_unique($uids);

		$members=self::getUserInfos($uids);

		include template('/offer/offer_view');
	}

	/**
	 * 删除回复
	 */
	function delete(){
		$this->Messager('操作成功','admin.php?mod=offer');
	}

	/**
	 * 展示创建悬赏页面
	 */
	public function create(){
		$zhb=self::getMyZhb();
		$this->Title = "发布悬赏";

		$config = $this->Config;
		include template('offer/offer_create');
	}

	public function normal(){
		if(MEMBER_ID < 1){
			$this->Messager("你需要先登录才能继续本操作", 'index.php?mod=login');
		}
	}
	/**
	 * 获取我的智慧币
	 */
	private function getMyZhb(){
		$memberInfo=M('members')->where('uid='.MEMBER_ID)->select();
		$memberInfo=$memberInfo[0];
		return $memberInfo[extcredits2];
	}

	/**
	 * 保存悬赏
	 */
	public function save(){
		$num=$_POST['num'];
		$day=$_POST['day'];

		$zhb=self::getMyZhb();;
		$config = $this->Config;



		//最小悬赏值不能小于设置
		if($num<$config['offer_point_min']){
			$this->err("悬赏分数不能少于".$config['offer_point_min']);
		}
		//最大悬赏只不能大于设置
		if($num>$config['offer_point_max']){
			$this->err("悬赏分数不能大于".$config['offer_point_max']);
		}
		//最小悬赏期限不能小于设置
		if($day<$config['offer_day_min']){
			$this->err("悬赏期限不能少于".$config['offer_day_min']."天");
		}
		//最大悬赏期限不能大于设置
		if($day>$config['offer_day_max']){
			$this->err("悬赏期限不能超过".$config['offer_day_max']."天");
		}

		//分数不能超过自己的智慧币
		if($zhb<$num){
			$this->err("智慧币不足");
		}

		//保存扣除登陆者积分
		$_POST['creadtisBecase']="发布悬赏";
		update_credits_by_action('postOffer',MEMBER_ID,1,$num);
		//修改不扣智慧币

		$offerInfo=M('offer');
		$offerInfo->create();
		$offerInfo->uid=MEMBER_ID;
		$offerInfo->startTime=time();
		$offerInfo->status=OfferConst::OFFER_INIT;
		$offerInfo->total=$_POST['num'];
		//计算结束天数
		$offerInfo->stopTime= time() + (24*60*60)*$_POST['day'];
		$ooid=$offerInfo->add();
		$this->succ("操作成功","index.php?mod=offer&code=offerList&id=".$ooid);
	}
	/**
	 * 删除悬赏
	 */
	public function del(){
		//只有管理员才可以删
		if ('admin' != MEMBER_ROLE_TYPE ){
			$this->err("你没有权限操作");
		}
		$offerInfo=M('offer');
		$offerInfo->create();
		$offerInfo->delete();
		$this->succ("操作成功");
	}

	/**
	 * 结贴操作
	 */
	public function toKnot(){

		//只有管理员和本人才能结贴
		$offerInfo=M('offer')->find($_POST['id']);
		if('admin' == MEMBER_ROLE_TYPE||$offerInfo['uid']==MEMBER_ID){
			$TofferInfo=M('offer');
			$TofferInfo->create();
			$TofferInfo->status=OfferConst::OFFER_KONT;
			$TofferInfo->save();
			self::backNum($offerInfo['id'], $offerInfo['num']);
		}else{
			$this->err("你没有权限操作");
		}


	}
	/**
	 * 结贴退还剩余智慧币
	 */
	private  function backNum($id,$num){
		//是否返还开关
		if(1==2){
			$offerInfo=M('offer');
			$offerInfo->id=$id;
			$offerInfo->num=0;
			$offerInfo->reNum=$num;
			update_credits_by_action('knotBack',$replyInfo['uid'],1,$num);
		}
	}


	/**
	 * 保存回复
	 */
	public function saveReply(){
		$replyInfo=M('offer_reply');
		$replyInfo->create();
		$replyInfo->uid=MEMBER_ID;
		$replyInfo->timeline=time();
		$replyInfo->add();

		self::addReplayNum($replyInfo);
		$this->succ("操作成功");
	}

	/**
	 * 采纳回复
	 */
	public function accept(){
		if(!$_POST['num']){
			$this->err('请填写分数');
		}

		$this->err('每个回复只能被采纳一次');


		
		
		
		$replyInfo=M('offer_reply')->find($_POST['id']);
		$num=$_POST['num'];
		//每个回复只能被采纳一次
		if($replyInfo['isWin']==1){
			$this->err('每个回复只能被采纳一次');
		}
		
		//最多只能采纳3个回复
		$vreplyInfos=M('offer_reply')->where('oid='.$replyInfo[oid])->select();
		if(count($vreplyInfos)>3){
			$this->err('最多只能采纳3个回复');
		}

		//发布者自己的回答不能被采纳
		if($replyInfo['uid']==MEMBER_ID){
			$this->err('不能采纳自己的回复');
		}

		$offerInfo=M('offer')->find($replyInfo[oid]);

		//如果到期了而发布者没有结贴，则发布者不能再采纳信息
		if($offerInfo['stopTime'] <= TIMESTAMP){
			$this->err(TIMESTAMP);
		}

		if($offerInfo['status']==OfferConst::OFFER_KONT){
			$this->err('此悬赏已结贴');
		}

		//金池剩余分数不足
		if($offerInfo['num']<$num){
			$this->err('剩余分数不足');
		}

		//采纳给金池-分
		$offerInfo['num']=$offerInfo['num']-$num;

		//采纳给回复者+分
		update_credits_by_action('replayOffer',$replyInfo['uid'],1,$num);


		//是否同时结贴
		if($_POST['kont']==1){
			$offerInfo[status]=OfferConst::OFFER_KONT;
			self::backNum($offerInfo['id'], $offerInfo['num']);
		}



		$offer_reply=M('offer_reply');


		$offer_reply->create();
		$offer_reply->isWin=1;
		$offer_reply->save();
		$this->Moffer->save($offerInfo);
		$this->succ("操作成功");
	}

	/**
	 * 删除回复
	 */
	public function delreply(){
		$replyInfo=M('offer_reply')->where('id='.$_POST['id'])->select();
		$replyInfo=$replyInfo[0];
		$offerInfo=M('offer')->find($replyInfo->oid);

		//只有楼主和管理员才能删除
		if($offerInfo['uid']!=MEMBER_ID||!XWB_S_IS_ADMIN){
			$this->err('没有权限操作');
		}
		$replyInfo=M('offer_reply');
		$replyInfo->create();
		$replyInfo->delete();
		$this->succ("操作成功");

	}
	/**
	 * 添加点击数
	 */
	private function addClickNum($offerInfo){
		$offerInfo[clickNum]=$offerInfo[clickNum]+1;
		$this->Moffer->save($offerInfo);
	}
	/**
	 * 添加回复数
	 */
	private function addReplayNum($replyInfo){
		$offerInfo=$this->Moffer->find($replyInfo->oid);
		$offerInfo[replayNum]=$offerInfo[replayNum]+1;
		$this->Moffer->save($offerInfo);
	}
	/**
	 * 超时的悬赏设置成超时状态
	 */
	public function vTimeOut(){
		//：：到期提前一天发提醒：：

		//取出结束时间比当前时间所有小于等于一天的
		$offerList=M('offer')->where('status=1 and isNotice=0 and (To_Days(NOW())-To_Days(FROM_UNIXTIME(stopTime)))>=-1')->select();
		$ids=array();

		//循环发送通知
		foreach ($offerList as $data){
			$ids[]=$data['uid'];
			$pm_content ="您发布的悬赏【".$data['title']
			."】马上就要到期，请<a href='index.php?mod=offer&code=offerList&id=103'>点击查看</a>";
			self::sendPm($ids,$pm_content);

			//设置为已提醒
			$offerInfo=M('offer');
			$offerInfo->id=$data['id'];
			$offerInfo->isNotice=1;
			$offerInfo->save();
		}

		//设置超时状态
		$Model = new Model() ;
		$Model->execute("update ".TABLE_PREFIX."offer set status='"
				.OfferConst::OFFER_TIMEOUT
				."' where status=1 and UNIX_TIMESTAMP()>stopTime");
	}
	/**
	 * 发私信
	 * @param unknown_type $ids
	 * @param unknown_type $pm_content
	 */
	private function sendPm($ids,$pm_content){
		$nickname_arr = array();
		$sql = "select `nickname` from `".TABLE_PREFIX."members` where `uid` in ('".implode("','", $ids)."')";
		$query = DB::query($sql);
		while(false != ($row = DB::fetch($query))) {
			$nickname_arr[] = $row['nickname'];
		}

		load::logic("pm");
		$PmLogic = new PmLogic();

		$post = array();
		if($nickname_arr){
			$post['to_user'] = implode(",",$nickname_arr);
			$post['message'] = $pm_content;
			$PmLogic->pmSend($post);
		}


	}

	/**
	 * 推荐
	 */
	public function recommend(){
		if ('admin' != MEMBER_ROLE_TYPE ){
			$this->err("只有管理员才可以操作");
		}
		$offerInfo=$this->Moffer;
		$offerInfo->create();
		$offerInfo->recommend=1;
		$offerInfo->save();
		$this->succ("操作成功");
	}
	/**
	 * 取消推荐
	 */
	public function unrecommend(){
		if ('admin' != MEMBER_ROLE_TYPE ){
			$this->err("只有管理员才可以操作");
		}
		$offerInfo=$this->Moffer;
		$offerInfo->create();
		$offerInfo->recommend=0;
		$offerInfo->save();
		$this->succ("操作成功");
	}



}

?>